/* TASK板块的切片 */
import {createSlice} from "@reduxjs/toolkit";
import {getTaskList} from "../../api/task"

const taskSlice = createSlice({
    // 设置切片名字
    name: 'task',
    // 设置切片对于 reducer 中的初始状态
    initialState: {
        taskList: null
    },
    // 编写不同业务下，对公共状态的更改
    reducers: {
        getAllTaskList(state, action) {
            // state: redux中的公共状态信息(基于 immer 库管理，无需自己再克隆)
            // action: 派发的行为对象，我们无需考虑行为标识的问题，都是以 action.payload 传递
            state.taskList = action.payload
        },
        removeTask(state, {payload}) {
            let taskList = state.taskList
            if (!Array.isArray(taskList)) return
            state.taskList = taskList.filter(item => {
                // payload:接受传递进来的，要删除那一项的 id
                return +item.id !== +payload
            })
        },
        updateTask(state, {payload}) {
            let taskList = state.taskList
            if (!Array.isArray(taskList)) return
            state.taskList = taskList.map(item => {
                if (+item.id == +payload) {
                    item.state = 2
                    item.complelte = new Date().toLocaleDateString('zh-Cn')
                }
                return item
            })
        }
    }
})

// 从切片中获取 actionCreator
export let {getAllTaskList, removeTask, updateTask} = taskSlice.actions

// 实现异步派发
export const getAllTaskListAsync = () => {
    return async dispatch => {
        let list = [];
        try {
            let result = await getTaskList(0)
            if (result.code === 0) {
                list = result.list
            }
        } catch (reason) {
        }
        dispatch(getAllTaskList(list))
    }
}

export default taskSlice.reducer